package com.example.blueconn.fragment.bl;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.blueconn.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhudongao
 * Desc
 * Date 4/5/21
 */

public class BlRecyclerAdapter extends RecyclerView.Adapter<BlRecyclerAdapter.BlViewHolder>{
    private List<BlBean> listData = new ArrayList<>();

    @NonNull
    @Override
    public BlViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_bl_select_layout, null);
        return new BlViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BlViewHolder holder, int position) {
        if (position >= 0 && position < listData.size()) {
            holder.setData(listData.get(position));
            holder.itemView.setOnClickListener(v -> {
                for (int i = 0; i < listData.size(); i++) {
                    if (position == i) {
                        listData.get(i).setChecked(true);
                    } else {
                        listData.get(i).setChecked(false);
                    }
                }
                notifyDataSetChanged();
            });
        }
    }

    public void addItem(BlBean bean) {
        listData.add(bean);
        notifyDataSetChanged();
    }

    public void clearData() {
        listData.clear();
    }

    public BlBean getSelectItem() {
        for (BlBean bl : listData) {
            if (bl.isChecked()) {
                return bl;
            }
        }
        return null;
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    public static class BlViewHolder extends RecyclerView.ViewHolder {
        private TextView blName;
        private ImageView blImg;
        private TextView blMac;
        public BlViewHolder(@NonNull View itemView) {
            super(itemView);
            blName = itemView.findViewById(R.id.bl_name);
            blMac = itemView.findViewById(R.id.bl_mac);
            blImg = itemView.findViewById(R.id.select_icon);
        }

        public void setData(BlBean blBean) {
            if (blBean.getBlName() == null || blBean.getBlName().isEmpty()) {
                blName.setText("未知设备");
            } else {
                blName.setText(blBean.getBlName());
            }
            blMac.setText(blBean.getMac());
            if (blBean.isChecked()) {
                blImg.setVisibility(View.VISIBLE);
            } else {
                blImg.setVisibility(View.GONE);
            }
        }
    }
}
